# ################################################################# #
#### LOAD LIBRARY AND DEFINE CORE SETTINGS                       ####
# ################################################################# #

### Clear memory
rm(list = ls())

### Load Apollo library
library(apollo)

### Set working directory to the folder of this script
apollo_setWorkDir()

### Initialise code
apollo_initialise()

### Set core controls
apollo_control = list(
  modelDescr      = "Tobit model for the daily hours of work in the time use data, censored at zero",
  indivID         = "indivID",
  outputDirectory = "output"
)

# ################################################################# #
#### LOAD DATA AND APPLY ANY TRANSFORMATIONS                     ####
# ################################################################# #

### Loading data from package
### if data is to be loaded from a file (e.g. called data.csv),
### the code would be: database = read.csv("data.csv",header=TRUE)
database = apollo_timeUseData
### for data dictionary, use ?apollo_timeUseData

### Daily hours of work, which are zero on most days
database$hours_work = database$t_a02/60

# ################################################################# #
#### DEFINE MODEL PARAMETERS                                     ####
# ################################################################# #

### Vector of parameters, including any that are kept fixed in estimation
apollo_beta = c(mu         = 0,
                b_fulltime = 0,
                b_weekend  = 0,
                b_female   = 0,
                sigma      = 5)

### Vector with names (in quotes) of parameters to be kept fixed at their starting value in apollo_beta, use apollo_fixed = c() if none
apollo_fixed = c()

# ################################################################# #
#### GROUP AND VALIDATE INPUTS                                   ####
# ################################################################# #

apollo_inputs = apollo_validateInputs()

# ################################################################# #
#### DEFINE MODEL AND LIKELIHOOD FUNCTION                        ####
# ################################################################# #

apollo_probabilities=function(apollo_beta, apollo_inputs, functionality="estimate"){

  ### Attach inputs and detach after function exit
  apollo_attach(apollo_beta, apollo_inputs)
  on.exit(apollo_detach(apollo_beta, apollo_inputs))

  ### Create list of probabilities P
  P = list()

  ### Calculate probabilities using Tobit model, with the hours of work censored at zero
  tobit_settings = list(outcomeTobit = hours_work,
                        xTobit       = b_fulltime*occ_full_time + b_weekend*weekend + b_female*female,
                        mu           = mu,
                        sigma        = sigma,
                        lowerLimit   = 0)

  P[["model"]] = apollo_tobit(tobit_settings, functionality)

  ### Take product across observation for same individual
  P = apollo_panelProd(P, apollo_inputs, functionality)

  ### Prepare and return outputs of function
  P = apollo_prepareProb(P, apollo_inputs, functionality)
  return(P)
}

# ################################################################# #
#### MODEL ESTIMATION                                            ####
# ################################################################# #

model = apollo_estimate(apollo_beta, apollo_fixed, apollo_probabilities, apollo_inputs)

# ################################################################# #
#### MODEL OUTPUTS                                               ####
# ################################################################# #

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO SCREEN)                               ----
# ----------------------------------------------------------------- #

apollo_modelOutput(model)

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO FILE, using model name)               ----
# ----------------------------------------------------------------- #

apollo_saveOutput(model)

# ################################################################# #
##### POST-PROCESSING                                            ####
# ################################################################# #

### Print outputs of additional diagnostics to new output file (remember to close file writing when complete)
apollo_sink()

# ----------------------------------------------------------------- #
#---- PREDICTIONS                                                ----
# ----------------------------------------------------------------- #

### The prediction is the expected value of the censored outcome, i.e. the expected hours of work on each day,
### including the probability of not working at all
predictions = apollo_prediction(model, apollo_probabilities, apollo_inputs)

### Mean predicted and observed hours of work, overall and for full-time workers on weekdays
mean(predictions[,3])
mean(database$hours_work)
mean(predictions[database$occ_full_time==1 & database$weekend==0, 3])
mean(database$hours_work[database$occ_full_time==1 & database$weekend==0])

# ----------------------------------------------------------------- #
#---- switch off writing to file                                 ----
# ----------------------------------------------------------------- #

apollo_sink()
